import React, { useEffect, useState } from 'react';
import './styles.css';
import { deleteChartUsingPOST, listMyChartByPageUsingPOST } from '@/services/arong/chartController';
import { Divider, Radio, Table, message, Space, Card, Tooltip, Pagination, Input, DatePicker, Select, Button, Tag } from 'antd';
import { MenuUnfoldOutlined, FormOutlined, DeleteOutlined, SyncOutlined, CloseCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { Link } from "react-router-dom"
import transferDate from '@/utils/dayUtils';



/**
 * 添加图表页面
 * @constructor
 */
const MyChartPage: React.FC = () => {


  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({});
  // 定义变量存储图表数据
  const [chartList, setChartList] = useState<API.Chart[]>();
  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');
  const [total, setTotal] = useState<number>(0); // 数据总数
  const [current, setCurrent] = useState<number>(1); // 当前页码
  const [pageSize, setPageSize] = useState<number>(10); // 每页显示条数
  const [loading, setLoading] = useState<boolean>(false);

  const { Search } = Input;

  interface DataType {
    id: number;
    name: string;
    chartType: string;
    goal: string;
    createTime: string;
    updateTime: string;
    status: string;
  }

  

  const loadData = async () => {
    setLoading(true);
    try {
      const res = await listMyChartByPageUsingPOST(searchParams);
      if(res.data) {
        setChartList(res.data.records ?? []);
        setTotal(res.data.total ?? 0);
      } else {
        message.error('获取我的图表失败');
      }
    } catch (e: any) {
        message.error('获取我的图表失败' + e.message);
    }
    setLoading(false);
  }

  // const detail = (record: any) => {
  //   console.log(record);
  //   this.props.history.replace(`/add_chart`);
  // }

  const del = async (record: any) => {
    setLoading(true);
    const id = record.id;
    await deleteChartUsingPOST({
      id,
    });
    loadData();
    setLoading(false);
  }

  const publish = async (record: any) => {
    console.log(record);
  }



  const columns: ColumnsType<DataType> = [
    {
          title: "序号",
          align: 'center',
          fixed: 'left',
          render: (text, record, index) => <div style={{textAlign: 'center'}}>{index + 1 + (current - 1) * pageSize}</div>
      },
    {
      title: '图表名称',
      dataIndex: 'name',
      align: 'center', // 列名居中对齐
      ellipsis: {
        showTitle: false,
      },
      render: text => <div style={{textAlign: 'center'}}>
        <Tooltip placement="topLeft" title={text}>
      {text}
    </Tooltip>
    </div>, // 数据居中对齐
    },
    {
      title: '图表类型',
      dataIndex: 'chartType',
      align: 'center', // 列名居中对齐
      render: text => <div style={{textAlign: 'center',  overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{text}</div>, // 数据居中对齐
    },
    {
      title: '分析目标',
      dataIndex: 'goal',
      align: 'center', // 列名居中对齐
      ellipsis: {
        showTitle: false,
      },
      render: text => <div style={{textAlign: 'center', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        <Tooltip placement="topLeft" title={text}>
      {text}
    </Tooltip>
    </div>, // 数据居中对齐
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center', // 列名居中对齐
      render: text => <div style={{textAlign: 'center'}}>{transferDate(text)}</div>, // 数据居中对齐
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      align: 'center', // 列名居中对齐
      render: text => <div style={{textAlign: 'center'}}>{transferDate(text)}</div>, // 数据居中对齐
    },
    {
      title: '操作',
      key: 'action',
      align: 'center', // 列名居中对齐
      render: (record) => (
        record.status === 'wait' || record.status === 'running' ? <Tag icon={<SyncOutlined spin />} color="processing">生成中...</Tag> :
        record.status === 'failed' ? <Tag icon={<CloseCircleOutlined />} color="error">生成失败</Tag> :
        <Space size="middle">
          <Link to={'/my_chart/detail/'+record.id}>
            <Button shape="circle" type='primary' icon={<MenuUnfoldOutlined />} size='small'/>
            </Link>
          <Button shape="circle" icon={<DeleteOutlined />} danger size='small' onClick={()=>del(record)}/>
        </Space>
      ),
    },
  ];


  const onSearch = async (mes: any) => {
    setSearchParams({
      name: mes,
    })
    
    loadData();
  } 

  const onSearchDate = async (mes: any) => {
    setSearchParams({
      createTime: mes,
    })
    
    loadData();
  } 

  
  const handleSelectChange = async (mes: any) => {
    setSearchParams({
      chartType: mes,
    })
    
    loadData();
  }


  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  const handlePage = (current: number, pageSize: number) => {
    setCurrent(current);
    setPageSize(pageSize);

    setSearchParams({
      ...searchParams,
      current: current,
      pageSize: pageSize,
    })
    loadData();
  }

  useEffect(() => {
    loadData();
  }, []);

  return (
    <div>
      <Card>
      <div className='.table'>
      <Radio.Group
        onChange={({ target: { value } }) => {
          setSelectionType(value);
        }}
        value={selectionType}
      >
      </Radio.Group>
      <h1>个人图表管理页面</h1>
      <Divider />
      <div style={{display: 'flex'}}>
        <div style={{display: 'inline-block', width: '350px', alignItems: 'center', marginRight: '50px'}}>
      <Search placeholder="请输入你要搜索的图表名称"  onSearch={onSearch} enterButton loading={loading} />
      </div>
      <div style={{display: 'inline-block', marginRight: '50px'}}>
      请选择日期：<DatePicker defaultValue={dayjs('2023-01-01', 'YYYY-MM-DD')} onChange={onSearchDate} format={'YYYY-MM-DD'} />
      </div>
      <div style={{display: 'inline-block'}}>
      请选择图表类型：<Select
      defaultValue=""
      style={{ width: 120 }}
      onChange={handleSelectChange}
      options={[
        { value: '折线图', label: '折线图' },
        { value: '柱状图', label: '柱状图' },
        { value: '堆叠图', label: '堆叠图' },
        { value: '饼图', label: '饼图' },
        { value: '雷达图', label: '雷达图' },
      ]}
    />
    </div>
    </div>
    <div style={{marginTop: '20px'}}>
      <Table
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }
      }
        rowKey={(record) => record.id}
        columns={columns}
        dataSource={chartList}
        bordered={true}
        pagination={false}
        style={{ width: 'min-context', tableLayout: 'fixed'}}
        loading={loading}
      />
      <Divider />
      <Pagination
        total={total}
        pageSize={pageSize}
        current={current}
        showSizeChanger
        showQuickJumper
        onChange={handlePage}
        showTotal={(total: any) => `总数据数： ${total}`}
        pageSizeOptions={[2, 5, 10, 20]}
      />
      </div>
    </div>
    </Card>
    </div>
  );
};


export default MyChartPage;
